package com.android.hz.czc.service.impl;

import com.android.hz.czc.entity.User;
import com.android.hz.czc.mapper.UserMapper;
import com.android.hz.czc.resultvue.Result;
import com.android.hz.czc.resultvue.ResultFactory;
import com.android.hz.czc.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hly
 * @since 2019-01-02
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result IRegister(User user) {
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())){
            return ResultFactory.buildFailResult("用户名或者密码不能为空");
        }
        userMapper.insert(user);
        return ResultFactory.buildSuccessResult(userMapper.selectById(user.getId()));
    }

    @Override
    public Result ILogin(User user) {
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())){
            return ResultFactory.buildFailResult("用户名或者密码不能为空");
        }
        User userDB = userMapper.selectOne(new UpdateWrapper<User>()
                .lambda().eq(User::getUsername,user.getUsername()).eq(User::getPassword,user.getPassword()));
        if (ObjectUtils.allNotNull(userDB)) {
            HttpSession session = request.getSession();
            session.setAttribute("user",userDB);
            log.info("欢迎“{}”成功登陆后台系统",userDB.getUsername());
            //查询到用户
            return ResultFactory.buildSuccessResult(userDB);
        }
        return ResultFactory.buildFailResult("登陆失败,没有该用户");
    }
}
